import requests
import json

from DataStructure.Course import UploadCourseModel
from DataStructure.Table import CourseTable
from Exception.CourseException import CreateCourseException
from Exception.TableException import CreateTableException, SwitchTableException, TableException

url_base = "https://i.xiaomixiaoai.com/course-multi-auth"

class Req:
    def __init__(self, auth_token: str):
        self.auth_token = auth_token
        self.headers = {
            'User-Agent': "Mozilla/5.0 (Linux; Android 13; MI 9 Build/TKQ1.221114.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/128.0.6613.146 Mobile Safari/537.36 MI 9; MIAI/6.127.8.0317 Build/506127008 Channel/MIUIV14.0.18.0.TFACNXM Device/cepheus OS/13 SDK/33 Flavors/upgrade ro.miui.ui.version.name/V140 PhoneLevel/High",
            'Accept': "application/json",
            'Accept-Encoding': "gzip, deflate, br, zstd",
            'Content-Type': "application/json",
            'sec-ch-ua': "\"Chromium\";v=\"128\", \"Not;A=Brand\";v=\"24\", \"Android WebView\";v=\"128\"",
            'sec-ch-ua-mobile': "?1",
            'authorization': self.auth_token,
            'access-control-allow-origin': "true",
            'sec-ch-ua-platform': "\"Android\"",
            'origin': "https://i.xiaomixiaoai.com",
            'x-requested-with': "com.miui.voiceassist",
            'sec-fetch-site': "same-origin",
            'sec-fetch-mode': "cors",
            'sec-fetch-dest': "empty",
            'referer': "https://i.xiaomixiaoai.com/h5/precache/ai-schedule/",
            'accept-language': "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
            'priority': "u=1, i",
            # 'Cookie': "<Cookie>"
        }

    def create_table(self, table_name: str) -> int:
      payload = {
          "name":  table_name,
          "current": 0,
          "sourceName": "course-app-miui"
      }

      response = requests.post(url_base + "/table", data=json.dumps(payload), headers=self.headers)
      res = response.json()

      print(res)
      if res["code"] != 0:
          raise CreateTableException(res["desc"])
      return res["data"]

    def switch_table(self,from_table_id: int, to_table_id: int) -> bool:
        payload = {
            "fromCtId": from_table_id,
            "toCtId": to_table_id,
            "sourceName": "course-app-miui"
        }

        response = requests.post(url_base + "/table_switch", data=json.dumps(payload), headers=self.headers)
        res = response.json()

        print(res)
        if res["code"] != 0:
            raise SwitchTableException(res["desc"])
        return res["data"]

    def create_course(self, data: UploadCourseModel) -> int:
        response = requests.post(url_base + "/courseInfo", data=data.to_json(), headers=self.headers)
        res = response.json()
        print(res)
        if res.get("code", 1) != 0:
            raise CreateCourseException(res)
        return res["data"]

    def _get_tables(self) -> list:
        response = requests.get(url_base + "/tables", headers=self.headers)
        res = response.json()
        print(res)
        return res["data"]

    def get_current_table(self) -> dict:
        tables = self._get_tables()
        for table in tables:
            if table["current"] == 1:
                return table
        return {}

    def modify_table(self, table: CourseTable):
        response = requests.put(url_base + "/table", data=table.to_json(), headers=self.headers)
        res = response.json()
        print(res)
        if res.get("code", 1) != 0:
            raise TableException(res)
        return res["data"]